<template>


  <div class="article-container">
      <!-- 导航栏 -->
    <van-nav-bar
      class="app-nav-bar"
      title="文章详情"
      left-arrow
      @click-left="$router.back()"
    />
    <!-- /导航栏 -->
  <div class="main-wrap">
      <!-- 加载中 -->
      <!-- <div class="loading-wrap">
        <van-loading
          color="#3296fa"
          vertical
        >加载中</van-loading>
      </div> -->
      <!-- /加载中 -->
      <!-- 加载完成-文章详情 -->
      <div class="article-detail">
        <!-- 文章标题 -->
        <h1 class="article-title">{{article.title}}</h1>
        <!-- /文章标题 -->
       <!-- 用户信息 -->
        <van-cell class="user-info" center :border="false">
          <van-image
            class="avatar"
            slot="icon"
            round
            fit="cover"
            :src="article.aut_photo"
          />
          <div slot="title" class="user-name">{{article.aut_name}}</div>
          <div slot="label" class="publish-date">{{article.pubdate | relativeTime}}</div>
          <van-button
            class="follow-btn"
            :type="article.is_followed ? 'default':'info'"
           
            round
            size="small"
            :icon="article.is_followed ? '':'plus'"
            @click="onFollow"
          >{{article.is_followed ? '已关注':'关注'}}</van-button>
          <!-- <van-button
            class="follow-btn"
            round
            size="small"
          >已关注</van-button> -->
        </van-cell>
        <!-- /用户信息 -->

         <!-- 文章内容 -->
        <div class="article-content markdown">

          <div v-html="article.content"
             ref="article-content"
          >

          </div>
           
        </div>
        <van-divider>正文结束</van-divider>
      </div>
       <!-- /加载完成-文章详情 -->
         <!-- 文章评论列表 -->
         <ArticleComment 
         :articleId="articleId" 
         :list="commentList"
         @click-reply="onReplyClick"
         @update-total-count="totalCommentCount=$event"
         />
         <!-- 文章评论列表 -->
      
        <!-- 底部区域 -->
    <div class="article-bottom">
      <van-button
        class="comment-btn"
        type="default"
        round
        size="small"
         @click="isPostShow = true"
      >写评论</van-button>
      <van-icon
        name="comment-o"
        :info="totalCommentCount"
        color="#777"
      />
      <van-icon
        :color="article.is_collected ?  'orange'  :'#777'"
        :name="article.is_collected ? 'star':'star-o' "
        @click="onCollect"
      />
      <van-icon
        :color="article.attitude===1 ?  'orange'  :'#777'"
       
        :name="article.attitude===1 ? 'good-job':'good-job-o' "
        @click="onLike"
      />
      <van-icon name="share" color="#777777"></van-icon>
    </div>
    <!-- /底部区域 -->
  </div>
  <!-- 发布文章评论 -->
<van-popup
  v-model="isPostShow"
  position="bottom"
>

 <post-comment  
 :target="articleId"
 @post-success="onPostSucess"
  />
</van-popup>
<!-- /发布文章评论 -->

<!-- 评论回复 -->
<van-popup
  v-model="isReplyShow"
  position="bottom"
  style="height: 95%"
>
  <comment-reply 
  :comment="curComment" 
  @click-close="isReplyShow=!isReplyShow"
  :articleId="articleId"
  v-if="isReplyShow"
  />
</van-popup>
<!-- /评论回复 -->
  </div>
</template>

<script>
import './markdown.css'
import { getArticleById } from '@/api/article'
import { ImagePreview } from 'vant';
import { addFollow, deleteFollow,addCollect,deleteCollect,addLike,deleteLike ,addComment} from '@/api/user'

import { mapState } from "vuex"
import ArticleComment from './components/article-comment'
import PostComment from './components/comment-post'
import CommentReply from './components/comment-reply'
export default {
  name: 'ArticleIndex',
  components: {ArticleComment,PostComment,CommentReply},
  props: {
    articleId: {
      type: [Number, String,Object],
      required: true
    }
  },
  data () {
    return {
      article: {}, // 文章详情
      isFollowLoading:false,
      isPostShow: false, //控制发布评论显示状态
      commentList:[],   //评论列表
      totalCommentCount:0,//评论总数量
      isReplyShow: false,
      curComment:{} // 点击回复的那个评论对象
        // 点击回复的那个评论对象
    }
  },
  computed: {
    ...mapState(['user'])
  },
  watch: {},
  created () {
    this.loadArticle()
  },
  mounted () {},
  methods: {
    async loadArticle () {
      try {
        const { data } = await getArticleById(this.articleId)
        this.article = data.data
      
       //数据改变影响视图更新(DOM数据)不是立即的
       //如果需要在修改数据之后马上操作被该数据影响的视图DOM，需要把这个代码方在$nextTick中
        //得到所有的img标签
      
      this.$nextTick(()=>{
       this.handlePreviewImage()
      })
     
        //循环img列表，给img注册点击事件


        //在事件处理中调用ImagePreview

      } catch (err) {
        console.log(err)
      }
    },
    handlePreviewImage(){

        //获取文章DOM容器
       const articleContent=this.$refs['article-content']
       const imags=  articleContent.querySelectorAll('img')
       const imgPaths=[]
       imags.forEach((img,index) => {
         imgPaths.push(img.src)
         img.onclick=function(){
            ImagePreview({
            images:imgPaths ,
            startPosition: index,
         });
         }
       });

    },
    async onFollow () {
      if (this.user){
  // 开启按钮的 loading 状态
      this.isFollowLoading = true
      try {
        // 如果已关注，则取消关注
        const authorId = this.article.aut_id
        if (this.article.is_followed) {
          await deleteFollow(authorId)
        } else {
          // 否则添加关注
          await addFollow(authorId)
        }

        // 更新视图
        this.article.is_followed = !this.article.is_followed
      } catch (err) {
        console.log(err)
        this.$toast.fail('操作失败')
      }

     // 关闭按钮的 loading 状态
     this.isFollowLoading = false
    }
    else{
      this.$dialog.confirm({
        title: '登录提示',
        message: '您还没有登录，点击登录？'
      })
        .then(() => { // 确认执行这里
        // 清除用户登录状态
        this.$router.push('/login')
      })
        .catch(() => { // 退出执行这里
        // on cancel
      })
    }
    },
    async onCollect(){
     if (this.user){
  // 开启按钮的 loading 状态
      this.$toast.loading({
        message:'操作中...',
        forbidClick:true //禁止背景点击
      })
      try {
        // 如果已收藏，则取消收藏
        
        const articleId = this.articleId
        if (this.article.is_collected) {
          await deleteCollect(articleId)
        } else {
          // 否则添加收藏
          await addCollect(articleId)
        }

        // 更新视图
        this.article.is_collected = !this.article.is_collected

        this.$toast.success(`${this.article.is_collected?'':'取消'}收藏成功`)
      } catch (err) {
        console.log(err)
        this.$toast.fail('操作失败')
      }

     // 关闭按钮的 loading 状态
     this.isFollowLoading = false
    }
    else{
      this.$dialog.confirm({
        title: '登录提示',
        message: '您还没有登录，点击登录？'
      })
        .then(() => { // 确认执行这里
        // 清除用户登录状态
        this.$router.push('/login')
      })
        .catch(() => { // 退出执行这里
        // on cancel
      })
    }
    },
     async onLike(){
      if (this.user){
  // 开启按钮的 loading 状态
      this.$toast.loading({
        message:'操作中...',
        forbidClick:true //禁止背景点击
      })
      try {
        // 如果已点赞，则取消点赞
        
        const articleId = this.articleId
        if (this.article.attitude===1) {
          await deleteLike(articleId)
          this.article.attitude=-1
        } else {
          // 没有点赞，新增点赞
          await addLike(articleId)
          this.article.attitude=1
        }

       

        this.$toast.success(`${this.article.attitude===1?'':'取消'}点赞成功`)
      } catch (err) {
        console.log(err)
        this.$toast.fail('操作失败')
      }

     // 关闭按钮的 loading 状态
     this.isFollowLoading = false
    }
    else{
      this.$dialog.confirm({
        title: '登录提示',
        message: '您还没有登录，点击登录？'
      })
        .then(() => { // 确认执行这里
        // 清除用户登录状态
        this.$router.push('/login')
      })
        .catch(() => { // 退出执行这里
        // on cancel
      })
    }
    },
    onPostSucess(comment){
     
     //把最新的评论列表放置在前面
    this.commentList.unshift(comment)
    this.isPostShow=false;
      this.totalCommentCount++
    },
    onReplyClick(comment){
      //console.log(obj)
      this.isReplyShow=true
     
      this.curComment=comment
    }
  }
  
 
}
</script>

<style scoped lang="less">
.article-container {
  .main-wrap {
    position: fixed;
    left: 0;
    right: 0;
    top: 46px;
    bottom: 44px;
    overflow-y: scroll;
    background-color: #fff;
  }
  .article-detail {
    .article-title {
      font-size: 20px;
      // padding: 50px 32px;
      padding: 14px;
      margin: 0;
      color: #3a3a3a;
    }

    .user-info {
      padding: 0 16px;
      .avatar {
        width: 35px;
        height: 35px;
        margin-right: 9px;
      }
      .van-cell__label {
        margin-top: 0;
      }
      .user-name {
        font-size: 12px;
        color: #3a3a3a;
      }
      .publish-date {
        font-size: 12px;
        color: #b7b7b7;
      }
      .follow-btn {
        width: 85px;
        height: 29px;
      }
    }

    .article-content {
      padding: 27px 16px;
      /deep/ p {
        text-align: justify;
      }
    }
  }

  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }

  .error-wrap {
    padding: 200px 32px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    .van-icon {
      font-size: 122px;
      color: #b4b4b4;
    }
    .text {
      font-size: 30px;
      color: #666666;
      margin: 33px 0 46px;
    }
    .retry-btn {
      width: 280px;
      height: 70px;
      line-height: 70px;
      border: 1px solid #c3c3c3;
      font-size: 30px;
      color: #666666;
    }
  }

  .article-bottom {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-sizing: border-box;
    height: 44px;
    border-top: 1px solid #d8d8d8;
    background-color: #fff;
    .comment-btn {
      width: 141px;
      height: 23px;
      border: 1px solid #eeeeee;
      font-size: 15px;
      line-height: 23px;
      color: #a7a7a7;
    }
    .van-icon {
      font-size: 20px;
      .van-info {
        font-size: 11px;
        background-color: #e22829;
      }
    }
  }
}
</style>